package com.imessage.action;

import com.bean.ManageResource;
import com.bean.ManageResourceRole;
import com.bean.ManageRoleUser;
import com.bean.ManageUser;
import com.imessage.comm.AdminSession;
import com.imessage.comm.Constants;
import com.imessage.jackson.JsonObject;
import com.imessage.type.BaseState;
import com.imessage.type.ManageResourceType;
import com.imessage.utils.MD5Encrypt;
import com.imessage.vo.LogonVo;
import com.imessage.web.HttpJson;
import io.ebean.Expr;
import io.ebean.Expression;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/admin/logon")
public class LogonAction extends BaseAction{
    /**
     * 管理员登录
     */
    @RequestMapping(value = "")
    public Object run(LogonVo logonVo) {
        JsonObject dataObject = new JsonObject();
        int statusCode = 300;
        String message = "参数不全";
        try {
            if (logonVo != null) {
                List<Expression> expressionList = new ArrayList<Expression>();
                expressionList.add(Expr.eq("name", logonVo.getUsername()));
                expressionList.add(Expr.eq("passwd", MD5Encrypt.MD5(logonVo.getPassword())));
                ManageUser manageUser = baseService.findObject(ManageUser.class, expressionList);
                if (manageUser != null) {
                    if (BaseState.normal.getCode().equals(manageUser.getState().getCode())) {
                        statusCode = 200;
                        message = "/admin/logon/index";
                        AdminSession adminSession = new AdminSession();
                        adminSession.setManageUser(manageUser);
                        HttpSession session = request.getSession();
                        session.setAttribute(Constants.SESSION_ADMIN_CODE, adminSession);
                    } else {
                        message = "账号被停用";
                    }
                } else {
                    message = "账号或密码错误";
                }
            }
        } catch (Exception e) {
            message = "服务错误";
            log.error("管理员登录错误", e);
        }
        dataObject.put("statusCode", statusCode);
        dataObject.put("message", message);
        return dataObject;
    }


    /**
     * 空白主页
     */
    @RequestMapping(value = "index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        HttpSession session = request.getSession();
        AdminSession session1 = (AdminSession) session.getAttribute(Constants.SESSION_ADMIN_CODE);
        if (session1!=null){
            modelAndView.addObject("name",session1.getManageUser().getName());
            modelAndView.setViewName("admin/index");
        } else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }


    /**
     * 菜单列表
     */
    @RequestMapping(value = "menulist")
    public Object menulist() {
        AdminSession adminSession = getAdminSession(Constants.ISDEBUG);//测试所有权限
        List resultlist = new LinkedList();
        if (adminSession == null) {
            return resultlist;
        }

        Map<Long, Long> userMenuMap = getUserMenuMap(adminSession.getManageUser().getId());
        List<ManageResource> parentlyqMenuList = getParentlyqMenuList();
        for (ManageResource parentManageResource : parentlyqMenuList) {
            List<ManageResource> ManageResourceList = getSubManageResourceList(parentManageResource.getId());
            List children = new LinkedList();
            for (Object obj : ManageResourceList) {
                ManageResource ManageResource = (com.bean.ManageResource) obj;
                if (!userMenuMap.containsKey(ManageResource.getId())) {
                    continue;
                }
                Hashtable childhash = new Hashtable();
                childhash.put("id", "menu" + ManageResource.getId());
                childhash.put("name", ManageResource.getName());
                childhash.put("target", "navtab");
                childhash.put("url", ManageResource.getUrl());
                children.add(childhash);
            }
            if (children.size() > 0) {
                Hashtable hash = new Hashtable();
                hash.put("name", parentManageResource.getName());
                hash.put("children", children);
                resultlist.add(hash);
            }
        }
        return resultlist;
    }


    private List<ManageRoleUser> getManageRoleUserList(Long manage_user_id) {
        List<Expression> expressionList = new ArrayList<Expression>();
        expressionList.add(Expr.eq("manageUserId", manage_user_id));
        return baseService.findList(ManageRoleUser.class, expressionList);
    }

    private List<ManageResourceRole> getManageResourceRoleList(Long manage_role_id) {
        List<Expression> expressionList = new ArrayList<Expression>();
        expressionList.add(Expr.eq("manageRoleId", manage_role_id));
        return baseService.findList(ManageResourceRole.class, expressionList);
    }


    protected Map<Long, Long> getUserMenuMap(Long manage_user_id) {
        List<ManageRoleUser> ManageRoleUserList = getManageRoleUserList(manage_user_id);
        Map<Long, Long> userMenuMap = new HashMap<Long, Long>();
        if (ManageRoleUserList == null
                || ManageRoleUserList.size() == 0) {
            return userMenuMap;
        }
        for (Object o : ManageRoleUserList) {
            ManageRoleUser ManageRoleUser = (com.bean.ManageRoleUser) o;
            List<ManageResourceRole> ManageResourceRoleList =
                    getManageResourceRoleList(ManageRoleUser.getManageRoleId());
            if (ManageResourceRoleList == null
                    || ManageResourceRoleList.size() == 0) {
                continue;
            }
            for (Object obj : ManageResourceRoleList) {
                ManageResourceRole ManageResourceRole = (com.bean.ManageResourceRole) obj;
                ManageResource ManageResource = baseService.findById(
                        com.bean.ManageResource.class, ManageResourceRole.getManageResourceId());
                if (ManageResource == null) {
                    baseService.delObject(ManageResourceRole);
                    continue;
                }
                userMenuMap.put(ManageResourceRole.getManageResourceId(), ManageResourceRole.getManageResourceId());
            }
        }
        return userMenuMap;
    }


    protected List<ManageResource> getSubManageResourceList(Long parent_manage_menu_id) {
        String order = "sort asc";
        List<Expression> expressionList = new ArrayList<Expression>();
        expressionList.add(Expr.eq("manage_high_resource_id", parent_manage_menu_id));
        List<ManageResource> ManageResourceList = baseService.findList(
                ManageResource.class, expressionList,"",order);
        if (ManageResourceList == null
                || ManageResourceList.size() == 0) {
            return new ArrayList<ManageResource>();
        }
        return ManageResourceList;
    }


    protected List<ManageResource> getParentlyqMenuList() {
        List<Expression> expressionList = new ArrayList<>();
        expressionList.add(Expr.eq("type", ManageResourceType.path.getCode()));
        List<ManageResource> parentlyqMenuList = new ArrayList<>();
        String order = " sort asc";
        List<ManageResource> manageMenuList = baseService.findList(ManageResource.class, expressionList, null, order);
        if (manageMenuList == null
                || manageMenuList.size() == 0) {
            return parentlyqMenuList;
        }
        for (Object o : manageMenuList) {
            ManageResource manageMenu = (ManageResource) o;
            if (manageMenu.getManageHighResourceId()==null
                    ||manageMenu.getManageHighResourceId() == 0) {
                parentlyqMenuList.add(manageMenu);
            }
        }
        return parentlyqMenuList;
    }


    @RequestMapping(value = "keepsession")
    public Object keepsession() {
        return new HttpJson();
    }

    /**
     * 空白主页
     */
    @RequestMapping(value = "mypage")
    public ModelAndView mypage(HttpServletResponse response) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin/main");
        return modelAndView;
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "out")
    public ModelAndView out(HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.removeAttribute(Constants.SESSION_ADMIN_CODE);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }
}
